package com.tssup.fesco.service.impl;

import com.tssup.fesco.common.cache.Cache;
import com.tssup.fesco.common.cache.redis.RedisKeyConstants;
import com.tssup.fesco.sales.ofc.persistent.mapper.OfcRStaticDataMapper;
import com.tssup.fesco.sales.ofc.persistent.pojo.OfcRStaticData;
import com.tssup.fesco.service.OfcStaticDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by jiashen on 17-4-7.
 */
@Service
public class OfcStaticDataServiceImpl implements OfcStaticDataService {

    @Autowired
    private Cache cache;

    @Autowired
    private OfcRStaticDataMapper ofcRStaticDataMapper;

    @Override
    public List<OfcRStaticData> getDatasByCodeAndKey(String staticCode, String staticKey, String parentKey) throws Exception {
        String Key = RedisKeyConstants.getRStaticDataKey( staticCode, staticKey, parentKey);

        List<OfcRStaticData> ret = (List<OfcRStaticData>) cache.get(Key, OfcRStaticData.class);
        if(ret == null){
            ret = ofcRStaticDataMapper.getDatasByCodeAndKey(staticCode, staticKey, parentKey);
            if(!CollectionUtils.isEmpty(ret)){
                cache.setex(Key, 3600, ret);
            }
        }

        return ret ;
    }

    /**
     * 只从缓存中读取数据，不会刷新缓存
     * @param staticCode
     * @param staticKey
     * @param parentKey
     * @return
     * @throws Exception
     */
    @Override
    public <T> List<T> getDatasByCodeAndKeyReadOnly(String staticCode, String staticKey, String parentKey, T t) throws Exception {
        String Key = RedisKeyConstants.getRStaticDataKey(staticCode, staticKey, parentKey);
        return (List<T>) cache.get(Key, t.getClass());
    }

    @Override
    public void setDataByCodeAndKey(List data, String staticCode, String staticKey, String parentKey) throws Exception {
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        String Key = RedisKeyConstants.getRStaticDataKey(staticCode, staticKey, parentKey);
        cache.setex(Key, 3600, data);
    }
}
